package com.opages.netty.demo.netty.stickybag;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * @author daizhong.liu
 * @create 2021-12-15 10:28
 **/
public class ClientProtocolHandler extends SimpleChannelInboundHandler<MessageProtocol> {
    private int count;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
//        for(int i=0;i<50;i++) {
//            ByteBuf byteBuf = Unpooled.copiedBuffer((i+"->hello,netty").getBytes(CharsetUtil.UTF_8));
//            ctx.writeAndFlush(byteBuf);
//        }

        for(int i=0;i<20;i++) {
            MessageProtocol protocol = new MessageProtocol();
            String content = i+":hello,netty";
            protocol.setContent(content.getBytes(CharsetUtil.UTF_8));
            protocol.setLen(content.getBytes().length);
            ctx.writeAndFlush(protocol);
        }
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {
//        byte[] bytes = new byte[msg.readableBytes()];
//        msg.readBytes(bytes);
//        String content = new String(bytes,CharsetUtil.UTF_8);
        System.err.println("客户端接收到的信息->\n"+msg.toString());
        System.out.println("客户端接收消息数量=" + (++this.count));

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.channel().close();
    }
}
